import 'package:flutter/material.dart';
import 'package:flutter_business_1907a/bean/category_child_bean_result.dart';
import 'package:flutter_business_1907a/bean/category_goods_bean_result.dart';
import 'package:flutter_business_1907a/bean/category_parent_bean_result.dart';
import 'package:flutter_business_1907a/provider/child_category_provider.dart';
import 'package:flutter_business_1907a/router/application.dart';
import 'package:flutter_business_1907a/service/service_method.dart';
import 'package:flutter_screenutil/screenutil.dart';
import 'package:provider/provider.dart';

class CategoryPage extends StatefulWidget {
  @override
  _CategoryPageState createState() => _CategoryPageState();
}

class _CategoryPageState extends State<CategoryPage> {
  List<CategoryParentBean> parentList;
  List<CategoryChildBean> childList;

  //请求一级列表的方法
  Future _getCategoryParent() async {
    await request('getGoodsParent', {'type': 0}, false).then(
        (value) => parentList = CategoryParentBeanResult.fromJson(value).data);
    _getCategoryChild(1);
    return parentList;
  }

  //请求二级列表的方法
  void _getCategoryChild(id) async {
    await request('getGoodsParent', {'type': id}, false).then(
        (value) => childList = CategoryChildBeanResult.fromJson(value).data);
    //获取到数据源之后,如果使用有状态的控件,则需要使用setState方法来刷新页面(类似于刷新适配器)
    //使用Provider后,则需要存到Provider中,下次获取直接从Provider中取
    Provider.of<ChildCategoryProvider>(context, listen: false)
        .setChildCategory(childList);
    _getCategoryGoodsList(childList[0].id, 1, 10); //todo 可能有bug
  }

  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size) async {
    await request('categoryGoodsList', '$id/$page/$size', true).then((value) =>
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .setCategoryGoodsList(
                CategoryGoodsBeanResult.fromJson(value).data.list));
  }

  //一级列表的item
  Widget _leftInkWell(index) {
    bool isClick = false;
    isClick = (index == Provider.of<ChildCategoryProvider>(context).parentIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        // Provider.of<ChildCategoryProvider>(context,listen: false).changeParentIndex(index);
        _getCategoryChild(parentList[index].id);
      },
      child: Container(
        height: ScreenUtil().setHeight(100),
        padding: EdgeInsets.only(left: 20, top: 15),
        decoration: BoxDecoration(
            color: isClick ? Colors.black26 : Colors.white,
            border:
                Border(bottom: BorderSide(width: 1, color: Colors.black12))),
        child: Text(
          parentList[index].categoryName,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }

  //一级分类的列表
  Widget _leftCategoryNav() {
    return Container(
      width: ScreenUtil().setWidth(180),
      decoration: BoxDecoration(
          border: Border(right: BorderSide(width: 1, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _leftInkWell(index);
        },
        itemCount: parentList.length,
      ),
    );
  }

  @override
  void initState() {
    // request('getGoodsParent', {'type': 1}).then(
    //     (value) => print(CategoryChildBeanResult.fromJson(value).data.length));
    print('initState');
    _getCategoryParent();
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ScreenUtil.init(context, height: 1334, width: 750);
    return Scaffold(
      appBar: AppBar(
        title: Text('分类'),
      ),
      body: Container(
        child: Row(
          children: [
            FutureBuilder(
              future: _getCategoryParent(),
              builder: (context, val) {
                if (val.hasData) {
                  return _leftCategoryNav();
                } else {
                  return Center(
                    child: Text('加载中'),
                  );
                }
              },
            ),
            Column(
              children: [
                //右侧上方的小导航
                RightCategoryNav(),
                //右侧下方具体商品列表
                CategoryGoodsList()
              ],
            )
          ],
        ),
      ),
    );
  }
}

class RightCategoryNav extends StatelessWidget {
  //请求三级列表的方法
  void _getCategoryGoodsList(id, page, size, context) async {
    await request('categoryGoodsList', '$id/$page/$size', true).then((value) =>
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .setCategoryGoodsList(
                CategoryGoodsBeanResult.fromJson(value).data.list));
  }

  //右侧上方导航的item
  Widget _rightInkWell(CategoryChildBean item, context, index) {
    bool isClick = false;
    isClick = (index == Provider.of<ChildCategoryProvider>(context).childIndex)
        ? true
        : false;
    return InkWell(
      onTap: () {
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .setChildId(item.id);
        _getCategoryGoodsList(
            item.id,
            Provider.of<ChildCategoryProvider>(context, listen: false).page,
            10,
            context);
        Provider.of<ChildCategoryProvider>(context, listen: false)
            .changeChildIndex(index);
      },
      child: Container(
        color: isClick ? Colors.pink : Colors.white,
        padding: EdgeInsets.fromLTRB(5.0, 10.0, 5.0, 10.0),
        child: Text(
          item.categoryName,
          style: TextStyle(fontSize: ScreenUtil().setSp(28)),
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    // List list = ['苹果', '联想', '外星人'];
    return Container(
      height: ScreenUtil().setHeight(80),
      width: ScreenUtil().setWidth(570),
      decoration: BoxDecoration(
          color: Colors.white,
          border:
              Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _rightInkWell(
              Provider.of<ChildCategoryProvider>(context)
                  .childCategoryList[index],
              context,
              index);
        },
        itemCount: Provider.of<ChildCategoryProvider>(context)
            .childCategoryList
            .length,
        scrollDirection: Axis.horizontal,
      ),
    );
  }
}

class CategoryGoodsList extends StatelessWidget {
  //商品图片
  Widget _goodsImage(index, context) {
    return Container(
      width: ScreenUtil().setWidth(200),
      child: Image.network(Provider.of<ChildCategoryProvider>(context)
          .categoryGoodsList[index]
          .goodsDefaultIcon),
    );
  }

  //商品名称
  Widget _goodsName(index, context) {
    return Container(
      width: ScreenUtil().setWidth(370),
      padding: EdgeInsets.all(5.0),
      child: Text(
        Provider.of<ChildCategoryProvider>(context)
            .categoryGoodsList[index]
            .goodsDesc,
        maxLines: 2,
        overflow: TextOverflow.ellipsis,
        style: TextStyle(fontSize: ScreenUtil().setSp(28)),
      ),
    );
  }

  //商品价格
  Widget _goodsPrice(index, context) {
    return Container(
      margin: EdgeInsets.only(top: 20.0),
      width: ScreenUtil().setWidth(370),
      child: Row(
        children: [
          Text(
            '价格:¥${Provider.of<ChildCategoryProvider>(context).categoryGoodsList[index].goodsDefaultPrice}元',
            style: TextStyle(fontSize: ScreenUtil().setSp(20)),
          ),
          Text(
            '原价:¥${Provider.of<ChildCategoryProvider>(context).categoryGoodsList[index].goodsDefaultPrice}元',
            style: TextStyle(
                fontSize: ScreenUtil().setSp(20),
                color: Colors.black26,
                decoration: TextDecoration.lineThrough),
          )
        ],
      ),
    );
  }

  //构建商品的Item
  Widget _listWidgetItem(index, context) {
    return InkWell(
      onTap: () {
        Application.router.navigateTo(context,
            '/detail?id=${Provider.of<ChildCategoryProvider>(context,listen: false).categoryGoodsList[index].id}');
      },
      child: Container(
        padding: EdgeInsets.only(top: 5.0, bottom: 5.0),
        decoration: BoxDecoration(
            color: Colors.white,
            border:
                Border(bottom: BorderSide(width: 1.0, color: Colors.black12))),
        child: Row(
          children: [
            _goodsImage(index, context),
            Column(
              children: [
                _goodsName(index, context),
                _goodsPrice(index, context),
              ],
            )
          ],
        ),
      ),
    );
  }

  @override
  Widget build(BuildContext context) {
    return Container(
      width: ScreenUtil().setWidth(570),
      height: ScreenUtil().setHeight(960),
      child: ListView.builder(
        itemBuilder: (context, index) {
          return _listWidgetItem(index, context);
        },
        itemCount: Provider.of<ChildCategoryProvider>(context)
            .categoryGoodsList
            .length,
      ),
    );
  }
}
